#include "Ball.h"
#include "QtMultimedia/qsound"

Ball::Ball()
{
    //set the speed
    speed = 5;
    xPos=yPos=-1;
    m_bStart = false;

    //random start position
    int StartX = 10;
    int StartY = 80;
    setPos(mapToParent(StartX,StartY));
}

QRectF Ball::boundingRect() const
{
    return QRect(0,0,20,20);
}

void Ball::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    QRectF rec = boundingRect();
    QBrush Brush(Qt::gray);

    //basic Collision detection

    QList<QGraphicsItem*> List = scene()->collidingItems(this);
    bool resEmpty = List.isEmpty();
    if(resEmpty)
    {
        //no collision
        Brush.setColor(Qt::green);
    }
    else
    {
        //collision!!!!
        Brush.setColor(Qt::red);

        //Set the position
        DoCollision(List[0]->boundingRect());
    }


    painter->fillRect(rec.x(),rec.y()/2, rec.width(), rec.height()/2,Brush);
    painter->drawRect(rec);

}

void Ball::advance(int phase)
{
    if(!phase) return;

    if(!m_bStart) return;

    setPos(mapToParent(xPos*speed, yPos*speed));
}

void Ball::DoCollision(QRectF rectLine)
{
    // |v 1,1
    // -> 1,-1  // h:   1,w: 601, xp: -300.5, yp:   99.5 bottom line
    // |^       // h: 401,w:   1, xp:  299.5, yp: -300.5 right line
    // <- 1,-1  // h:   1,w: 601, xp: -300.5, yp: -300.5 top line
    if(rectLine.height() > 50) // side lines
    {
        xPos *= -1;
        yPos *= 1;
    }
    else// if(rectLine.width() > 600 && rectLine.y() < -300) // top line
    {
        xPos *= 1;
        yPos *= -1;
    }
    QString sound("chord.wav");
    QSound::play(sound);
}
